<?php

class MysqlQuery {
    private $result;
    private $cast_func = array();
    
    public static function cast_int(&$val) { $val = (int) $val; }
    public static function cast_float(&$val) { $val = (float) $val; }
    
    public function __construct($db,$query,$cast = false) {
        assert('$db instanceof bg_mysqli;');
        $result = $db->query($query);
        if (!$result) throw new Exception($db->error." $query");

        if ($cast) {
            while ($finfo = $result->fetch_field()) {
                switch ($finfo->type) {
                    case 1:
                    case 2:
                    case 3:
                    case 8:
                    case 9:
                    case 16:
                        $this->cast_func[$finfo->name] = 'self::cast_int';
                        break;
                    case 4:
                    case 5:
                    case 246:
                        $this->cast_func[$finfo->name] = 'self::cast_float';
                        break;
                }
            }
        }
        $this->result = $result;
    }
    
    public function get_array ($keyfield = null) {
        $array = array();
        $cast = count($this->cast_func);
        while ($row = $this->result->fetch_assoc()) {
            foreach ($this->cast_func as $key=>$cast_fcn) {
                if (isset($row[$key])) call_user_func_array($cast_fcn,array(&$row[$key]));
            }
            if ($keyfield === null) $array[] = $row;
            else $array[$row[$keyfield]] = $row;
        }
        return $array;
    }
    
    public function get_atom () {
        return $this->result->fetch_row()[0];
    }
}
?>